import { useRef, useState } from 'react';
import { LabASR } from 'byted-ailab-speech-sdk';
import { buildFullUrl, getToken } from '../util/helps';
const ASRStory = () => {
  const [header, setHeader] = useState('');
  const [content, setContent] = useState('');
  const [fullResponse, setFullResponse] = useState({});
  const recordStopping = useRef(false);
  const [asrClient] = useState(
    LabASR({
      onMessage: async (text, fullData) => {
        setContent(text);
        setFullResponse(fullData);
      },
      onStart() {
        setHeader('正在录音');
        setContent('');
      },
      onClose() {
        setHeader('录音结束');
      },
    })
  );
  const startASR = async () => {
    recordStopping.current = false;
    // const appid = '5075494287'
    const appid = '4607500527'
    const accessKey = 'Nmtj3o5a5mQSZgkuOcUZ3VQthE6tcR1G'
    const auth = {};
    // 大模型
    // const token = await getToken(appid, accessKey);
    // const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiNTA3NTQ5NDI4NyJdLCJleHAiOjE3NDc5MzQyMDN9.-4DRE1ViEaJw_6ud9gyJIMUB5-CSHDkuHLmiLeoSaJ0';
    const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiNDYwNzUwMDUyNyJdLCJleHAiOjE3NDc5MDM0MjN9.qrnqgUsQ2NO4iv1vlS3ZSWPsA8UoNHl7zGyFhr8FFuc';
    if (token) {
      auth.api_resource_id = 'volc.bigasr.sauc.duration';
      auth.api_app_key = appid;
      auth.api_access_key = `Jwt; ${token}`;
    }
    const fullUrl = buildFullUrl(`wss://openspeech.bytedance.com/api/v3/sauc/bigmodel`, auth);
    const params = {
      url: fullUrl,
      config: {
        user: {
          uid: 'byted sdk demo',
        },
        audio: {
          format: 'pcm',
          rate: 16000,
          bits: 16,
          channel: 1,
        },
        request: {
          model_name: 'bigmodel',
          show_utterances: true,
        },
      },
    };
    asrClient.connect(params);
    await asrClient.startRecord({}, async (recordResult) => {
      // 音频采集数据，可用于音频可视化需要
      const rawData = await recordResult.arrayBuffer();
      console.warn('rawData:', rawData);
    });
  };
  const stopASR = () => {
    // 正在关闭中...
    if (recordStopping.current) {
      return;
    }
    recordStopping.current = true;
    asrClient.stopRecord();
  };
  return (
    <div>
      <button id='start' onClick={startASR}>
        开始说话
      </button>
      <button id='stop' onClick={stopASR}>
        结束说话
      </button>
      <div id='text-header'>{header}</div>
      <div id='text-content'>{content}</div>
      {/* <pre>{JSON.stringify(fullResponse, null, 2)}</pre> */}
    </div>
  );
};

export default ASRStory;